var express = require('express');
 import  AdminModel from '../../models/admin/admin';
// var adminModel = require('../../models/admin/admin');
// var baseComponent = require('../../prototype/baseComponent.js');
// var baseComponent1 = new baseComponent();
// var timeformet = require('time-formater');
// var formidable = require('formidable');
var md5 = require('md5-nodejs');
var router = express.Router();
import Admins from '../../models/admin/admin'
import dtime from 'time-formater'
import formidable from "formidable"
import ids from '../../prototype/ids'
import crypto from 'crypto'
// import mongodb from 'mongodb'
class Admin extends ids{
    constructor(){
        super();
        this.login = this.login.bind(this) // 让login方法中的指向自己
    }
    loginout(req,res,next){
        delete req.session.user_id
        res.send({
            err:1
        })


    }
    adminList(req,res,next){
        adminModel.find({}, function (err, dataadmin) {

            if (dataadmin != null) {
                console.log(dataadmin);
                res.send({
                    err: 1,
                    msg: '查询成功',
                    info:dataadmin
                });
                return;
            } else {
                res.send({
                    err: 0,
                    msg: '登录失败,用户名或密码错误'
                });
                return;
            }
        })
    }

    // adminLogin(req,res,next){
    //
    //     adminModel.findOne({ user_name: req.body.user_name, password: md5(req.body.password) }, function (err, dataadmin) {
    //         if (dataadmin != null) {
    //             console.log(dataadmin);
    //             req.session.user_id = dataadmin.id;
    //             res.send({
    //                 err: 1,
    //                 msg: '登录成功',
    //                 imgpath: dataadmin.avatar
    //             });
    //             return;
    //         } else {
    //             res.send({
    //                 err: 0,
    //                 msg: '登录失败,用户名或密码错误'
    //             });
    //             return;
    //         }
    //     })
    // }
    async adminCount1(req,res,next){
        const form= new formidable.IncomingForm();
        // console.log("***")
        form.parse(req,(err,fields,files) => {
            res.send({
                fields:fields,
                files:files
            })
        })
    }
    async test(req,res,next){
        const form= new formidable.IncomingForm();
        // console.log("***")
        form.parse(req,(err,fields,files) => {
            res.send({
                fields:fields,
                files:files
            })
        })
    }
    async adminExit(req, res, next){
        try {
            delete req.session.admin_id
            console.log(req.session)
            res.send({err: 1,message:"退出成功"})
        }catch (e) {
            res.send({err:0,message:"退出失败"})

        }

    }
     async autoLogin(req, res, next){
            // console.log(req.session)
            if(req.session.admin_id){
                // console.log(req.session)
                var result = await Admins.find({
                    id:req.session.admin_id
                })
                // console.log(result)
                res.send({err:1,message:"自动登陆",user_name:result[0].user_name})
            }else {
                res.send({err:0,message:"没有登陆状态"})
            }
    }
    async login(req,res,next){
        try {
            console.log(req.body)
            const md5 = crypto.createHash('md5');
            let pw = md5.update(req.body.password).digest('base64')
            // console.log(pw)
            // var pw = req.body.password
            var result = await Admins.find({
                user_name:req.body.user_name
            })
            // console.log(result)
            if(result.length >= 1){
                // console.log(req.body)
                // var result1 = await Admins.find({
                //     user_name:req.body.user_name,
                //     password:req.body.password
                // })
                // console.log(result1.length);
                if(result[0].password.toString() === pw.toString() ){
                    req.session.admin_id = result[0].id;
                    // console.log(req.session)
                    res.send({err:1,message:'登陆成功！'})
                }else {
                    // console.log(req.body)
                    res.send({err:0,message:'密码错误！'})
                }
            }else{
                let no = await this.setID("admin_id");
                let admin = new Admins({
                    user_name: req.body.user_name,
                    password: pw,
                    // id: req.body.id,
                    default: '管理员',
                    id:parseInt(no),
                    create_time: dtime().format('YYYY-MM-DD'),
                    status: 1, //1:普通管理、 2:超级管理员
                    city: "西安"
                });
                await admin.save((res,err) => {
                    // console.log(res)
                    // console.log(err)
                })
                req.session.admin_id = no;
                res.send({err:1,message:'已自动创建账户！登陆成功！'})
            }
        }catch (e) {
            console.log(e)
            res.send({err:0,message:'登陆状态异常'})
        }

    }
    async getList(req,res,next) {
        // res.header("Access-Control-Allow-Origin", "http://localhost:8001");
        // res.header("Access-Control-Allow-Credentials",true);
        // res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
        // res.header("Access-Control-Allow-Headers","*")
        // console.log(req.cookies)
        // res.cookie('isFirst', 1, { maxAge: 60 * 1000});
        let {limit = 10, offset = 0} = req.query;
        let result1 = await Admins.count()
        var result = await Admins.find().sort({id:1}).limit(Number(limit)).skip(Number(offset));
        res.send({status:1,count:result1,result})
    }
    async getOne(req,res,next) {
        // res.header("Access-Control-Allow-Origin", "*");
        var result = await Admins.find({
            _id:req.body._id
        });
        res.json(result)
    }
    async del(req,res,next){
        // res.header("Access-Control-Allow-Origin", "*");
        // res.header("Access-Control-Allow-Methods","GET, POST, OPTIONS, PUT, DELETE")
        // res.header("Access-Control-Allow-Credentials",true)
        var result = await Admins.where({
            _id:req.body._id
        }).remove();
        res.send({result,status:1})
    }
    async update(req,res,next){
        // res.header("Access-Control-Allow-Origin", "*");
        let result1 = await Admins.find({
            _id:req.body._id
        }).update({
            password:req.body.password,
            city:req.body.city
        })
        res.json(result1)
    }

    async allAdmin(req,res,next){
        // res.header("Access-Control-Allow-Origin", "*");
        try {
            let result1 = await Admins.find()
            res.send({status:1,count:result1.length})
        }catch (e) {
            res.send({status:0,count:0,err:"ERR_GET_ADMIN_COUNT"})
        }
    }
    async deleteAdmin(req,res,next){
        var { id } = req.query
        var result = await Admins.findOne({id}).delete()
        res.send({result})
    }
    async adminCount(req,res,next){
        console.log(req.params.date)
        const date=req.params.date;
        if(!date){
            res.send({
                status: 0,
                type: 'ERROR_PARAMS',
                message: '参数错误'
            });
            return
        }
        try{
            const count = await AdminModel.find({
                create_time: eval('/^' + date + '/gi')
            }).count();
            res.send({
                status: 1,
                count: count
            })
        }catch (e) {
            console.log(e)
            res.send({
                status: 0,
                type: "ERROR_GET_ORDER_REGISTE_COUNT",
                message: "获取当天管理员失败"
            })
        }
    }
    async allAdminCount(req,res,next){
        try{
            const count = await AdminModel.count();
            res.send({
                status: 1,
                count: count
            })
        }catch (e) {
            res.send({
                status: 0,
                type: "ERROR_GET_ADMIN_REGISTE_COUNT",
                message: "获取管理员失败"
            })
        }
    }
}
export default new Admin()

